#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module vehiclestype ."""

## SQL type wrappers audited by Joshua Kugler, 2008-02-20

from string import Template
from tack.db import query
from tack.lib import string_app, content_headers, status_codes, json_app
from tack.lib.jsontools import json_dumps
from tack.lib.dicttools import query_to_list
import time

select_all_types = """
SELECT vt_id, vt_description, vt_image_url
FROM tmpo_vehicle_type
"""

select_type_data = Template("""
SELECT vt_id, vt_description, vt_image_url
FROM tmpo_vehicle_type
WHERE vt_id = $type_id
""")

insert_type = Template("""
INSERT INTO tmpo_vehicle_type (vt_description, vt_image_url)
VALUES ( '$description', '$url' )
""")

update_type_by_id = Template("""
UPDATE tmpo_vehicle_type
SET vt_description='$description', vt_image_url='$vt_image_url'
WHERE vt_id = $type_id
""")

logical_delete_type = Template("""
DELETE FROM tmpo_vehicle_type 
WHERE vt_id = $type_id
""")


def get_all_types(environ, start_response):
    sql_statement = select_all_types
    rows = query(environ['connection'], sql_statement)
    output = {}
    labels = ['id','description','url'] 
    output['types'] = [dict(zip(labels,i)) for i in rows]
    return json_app(output)(environ, start_response)

def get_type_data(environ, start_response):
    sql_statement = select_type_data.substitute(
     type_id = environ['dispatcher.groups']['type_id']
    )
    rows = query(environ['connection'], sql_statement)
    output = {}
    labels = ['id','description','url']
    output['types'] = [dict(zip(labels,i)) for i in rows]
    return json_app(output)(environ, start_response)

def add_type(environ, start_response):
    form = environ['form']
    sql_statement = insert_type.substitute(
     description = sql_string(form['description']),
     url = sql_string(form['url'])
    )
    query(environ['connection'], sql_statement)
    rows = query(environ['connection'], 'SELECT @@IDENTITY')
    return json_app(rows)(environ, start_response)

def update_type(environ, start_response):
    form = environ['form']
    sql_statement = update_type_by_id.substitute(
     type_id = environ['dispatcher.groups']['type_id'],
     description = sql_string(form['description']),
     url = sql_string(form['url'])
    )
    rows = query(environ['connection'], sql_statement)
    output = 'Type Updated'
    return json_app(output)(environ, start_response)

def delete_type(environ, start_response):
    sql_statement = logical_delete_type.substitute(
    type_id = environ['dispatcher.groups']['type_id']
    )
    rows = query(environ['connection'], sql_statement)
    output = 'Type Deleted'
    return json_app(output)(environ, start_response)
